package src.main.java.org.netWorkProgram.TCP.demo4;

import java.io.*;
import java.net.Socket;

public class ServerReaderThread extends Thread{
    private Socket socket;
    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            DataInputStream dataInputStream = new DataInputStream(inputStream);
            while(true){
                try {
                    String s = dataInputStream.readUTF();
                    System.out.println(s);
                    //把消息分发给全部客户端
                    sendMsgToAll(s);
                } catch (Exception e) {
                    System.out.println("有人下线了，"+socket.getRemoteSocketAddress());
                    Server.onLineSockets.remove(socket);
                    dataInputStream.close();
                    socket.close();
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void sendMsgToAll(String msg) throws Exception {
        //发送给所有在线socket管道接收
        for (Socket onLineSocket : Server.onLineSockets) {
            OutputStream outputStream = onLineSocket.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
            dataOutputStream.writeUTF(msg);
            dataOutputStream.flush();
        }
    }
    public ServerReaderThread(Socket socket){
        this.socket = socket;
    }
}
